package com.lizhenhua.orderclose.service.impl;


import com.lizhenhua.fmmall.beans.OrderItem;
import com.lizhenhua.fmmall.beans.Orders;
import com.lizhenhua.fmmall.beans.ProductSku;
import com.lizhenhua.orderclose.feiclient.QueryOrderItemFeignClient;
import com.lizhenhua.orderclose.feiclient.QueryProductSkuFeignClient;
import com.lizhenhua.orderclose.feiclient.UpdateOrderStatusFeignClient;
import com.lizhenhua.orderclose.feiclient.UpdateProductStockFeignClient;
import com.lizhenhua.orderclose.mapper.OrderCloseMapper;
import com.lizhenhua.orderclose.service.OrderCloseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderCloseServiceImpl implements OrderCloseService {

    @Autowired
    private UpdateOrderStatusFeignClient updateOrderStatusFeignClient;
    @Autowired
    private QueryOrderItemFeignClient queryOrderItemFeignClient;

    @Autowired
    private QueryProductSkuFeignClient productSkuFeignClient;

    @Autowired
    private UpdateProductStockFeignClient productStockFeignClient;

    @Override
    public int closeOrder(String orderId, int closeType) {
        int i = 0; // 判断是否执行成功

        // 1. 调用order-status-update 服务  修改订单状态为6
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setStatus("6");
        orders.setCloseType(1);
        int update = updateOrderStatusFeignClient.update(orders);
        System.out.println(update);

        // 2. 调用orderitem-query 服务 查询当前包含的商品信息（订单快照）
        if (update > 0) {
            List<OrderItem> orderItems = queryOrderItemFeignClient.queryOrderItem(orderId);
            //3. 还原库存 调用 stock-update 服务 修改库存
            if (orderItems != null && orderItems.size() > 0) {

                // 存放 productSku  的 数组
                List<ProductSku> productSkus = new ArrayList<>();
                for (OrderItem o : orderItems
                ) {
                    ProductSku productSku = productSkuFeignClient.query(o.getSkuId());
                    int newStock = productSku.getStock() + o.getBuyCounts();
                    // 把新库存设置到里面
                    productSku.setStock(newStock);
                    productSkus.add(productSku);
                }
                // 修改库存
                i = productStockFeignClient.update(productSkus);

            }

        }
        // 如果 i>0 才还原成功
        return i;


    }
}
